<template>
    <div class="swiperPhoto">
        <div class="swiper-container" ref="swiperContainer">
            <div class="swiper-wrapper" :style="wrapperStyle">
                <div v-for="(item, index) in displayImages" :key="index" class="swiper-slide" :style="slideStyle">
                    <img :src="item" :style="imageStyle" />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'

const props = defineProps({
    images: {
        type: Array,
        default: () => []
    },
    width: {
        type: [String, Number],
        default: '524px'
    },
    height: {
        type: [String, Number],
        default: '300px'
    },
    speed: {
        type: Number,
        default: 1
    },
    delay: {
        type: Number,
        default: 0
    }
})

// 复制两份图片数组以实现无缝循环滚动
const displayImages = computed(() => [...props.images, ...props.images])

const slideStyle = computed(() => ({
    width: typeof props.width === 'number' ? `${props.width}px` : props.width,
    height: typeof props.height === 'number' ? `${props.height}px` : props.height,
    flexShrink: 0
}))

const imageStyle = computed(() => ({
    width: '100%',
    height: '100%',
    objectFit: 'cover'
}))

const swiperContainer = ref(null)
const position = ref(0)
const wrapperStyle = computed(() => ({
    transform: `translateX(${-position.value}px)`,
    transition: 'transform 0.5s linear'
}))

let animationId = null
let timeoutId = null

const animate = () => {
    const containerWidth = swiperContainer.value?.clientWidth || 0
    const slideWidth = parseInt(props.width) + 10 // 加上gap的宽度
    const totalWidth = slideWidth * props.images.length

    position.value += props.speed

    // 当滚动到第一组图片的末尾时，立即重置到开始位置
    if (position.value >= totalWidth) {
        position.value = 0
    }

    animationId = requestAnimationFrame(animate)
}

onMounted(() => {
    timeoutId = setTimeout(() => {
        animationId = requestAnimationFrame(animate)
    }, props.delay)
})

onUnmounted(() => {
    if (animationId) {
        cancelAnimationFrame(animationId)
    }
    if (timeoutId) {
        clearTimeout(timeoutId)
    }
})
</script>

<style scoped>
.swiperPhoto {
    width: 100%;
    overflow: hidden;
}

.swiper-container {
    width: 100%;
    overflow: hidden;
}

.swiper-wrapper {
    display: flex;
    flex-wrap: nowrap;
    gap: 15px;
}

.swiper-slide {
    display: flex;
    justify-content: center;
    align-items: center;
}
img {
    display: block;
}
</style>
